<!-- 转移审计申请单 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="proposer" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptIdText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptIdText"
          ></h-select-depart-input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">项目信息</view>
        <u-form-item label="项目名称" prop="projectId" required>
          <h-select-project-input-popup
            :api="queryDistributionProjectList"
            :proDisabled="true"
            :projectStatus="'2'"
            ref="projectSelect"
            v-model="model.projectId"
            style="width: 100%"
            placeholder="请选择项目名称"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-project-input-popup>
          <!-- @change="projectChangeHandle" -->
        </u-form-item>
        <u-form-item label="项目编号" prop="projectNo">
          <u--input disabled placeholder="请输入项目编号" v-model="model.projectNo"></u--input>
        </u-form-item>
        <u-form-item label="合同名称" prop="contractId">
          <h-select-contract-manager-input-popup
            disabled
            :status="'2'"
            :allList="true"
            :signUnit="model.signUnit"
            :muitFlag="true"
            v-model="model.contractId"
            :contact-name.sync="model.contractName"
            placeholder="请选择合同名称"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-contract-manager-input-popup>
        </u-form-item>
        <u-form-item label="项目承接人" prop="undertaker">
          <h-select-person-input-popup
            disabled
            v-model="model.undertaker"
            style="width: 100%"
            placeholder="请选择项目承接人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="经营团队" prop="managementTeam">
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.managementTeam"
            objectField="model.managementTeam"
            placeholder="请选择经营团队"
            border="surround"
            :tdlx="1"
          />
        </u-form-item>
        <u-form-item label="生产团队" prop="productionTeam">
          <u--input v-model="model.productionTeam" disabled></u--input>
          <!-- <h-select-team-input
            disabled
            :isMulti="true"
            style="width: 100%"
            v-model="model.productionTeam"
            objectField="model.productionTeam"
            placeholder="请选择生产团队"
            border="surround"
            :tdlx="2"
          /> -->
        </u-form-item>
        <u-form-item label="业绩归属年度" prop="year">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.year"
            objectField="model.year"
            placeholder="请选择业绩归属年度"
            border="surround"
            dictName="yjgsnd"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="签订单位" prop="signUnit">
          <h-select-company-input-popup
            disabled
            style="width: 100%"
            v-model="model.signUnit"
            commercialType="1"
            placeholder="请选择公司"
            border="surround"
          ></h-select-company-input-popup>
        </u-form-item>
        <u-form-item label="业主单位" prop="ownerUnit">
          <h-select-customer-input-popup
            disabled
            style="width: 100%"
            v-model="model.ownerUnit"
            objectField="model.ownerUnit"
            commercialType="1"
            placeholder="请选择业主单位"
            border="surround"
          ></h-select-customer-input-popup>
        </u-form-item>
        <u-form-item label="移交说明" prop="instruction" required>
          <u--textarea maxlength="500" confirm-type="send" v-model="model.instruction" placeholder="请输入移交说明"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">移交信息</view>
        <ErpAuditTransferApplicationFormInfo :dictOptions="dictOptions" :entities="instructionDataSource" />
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">任务附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.taskFile" :isIcon="false"></h-upload-file>
          <file-list v-if="model.taskFile" v-model="model.taskFile" :isDelete="true"></file-list>
        </view>
      </view>
      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx"></view>
      <u-toast ref="uToast"></u-toast>
      <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
    </u-form>
  </view>
</template>
    
    <script>
import { mapState } from 'vuex'
import moment from 'moment'
// import Decimal from 'decimal.js'
import {
  gainBillNo,
  add,
  edit,
  info,
  queryContractFinal,
  queryProjectTaskList,
  queryProgressPaymentNode,
  queryErpAuditTransferApplicationInfo,
} from '@/api/audit/ErpAuditTransferApplicationForm.js'
import { queryDistributionProjectList } from '@/api/index'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import fileList from '@/pages/synergy/components/fileList.vue'
// import Form from './components/PaybackDisclaimerForm.vue'
// import FormInfo from './components/PaybackDisclaimerFormInfo.vue'
import ErpAuditTransferApplicationFormInfo from './components/ErpAuditTransferApplicationFormInfo.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗

export default {
  name: 'ErpAuditTransferApplicationForm',
  components: {
    fileList,
    // Form,
    // FormInfo,
    ErpAuditTransferApplicationFormInfo,
    ProcessNodeConfiguration,
  },
  data() {
    return {
      queryDistributionProjectList,
      isSubmit: false, // 控制按钮是否可以点击
      index: null,
      showFormModal: false,
      loading: false,
      id: '',
      basicForm: {},
      dictOptions: {},
      formData: [],
      instructionDataSource: [],
      model: {
        bpmBizTitle: '',
        billNo: '',
        createTime: '',
        proposer: '',
        proposerDeptId: '',
        managementTeam: '',
        projectId: '',
        projectNo: '',
        undertaker: '',
        productionTeam: '',
        productionTeamId: '',
        year: '',
        signUnit: '',
        ownerUnit: '',
        contractId: '',
        instruction: '',
        taskFile: null,
      },
      rules: {
        billNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
        proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
        proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
        createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
        projectId: [{ required: true, message: '请选择项目名称!', trigger: ['blur', 'change'] }],
        instruction: [{ required: true, message: '请输入移交说明!', trigger: ['blur', 'change'] }],
      },
      projectLeadingToSubTable: '',
      projectLeadingToSubTableText: '',
      projectIdBackups: null,
      //代码生成后需手动设置流程编码
      flowCode: 'onl_erp_audit_transfer_application',
      formUrl: 'erp/audit/auditTransferApplication/modules/ErpAuditTransferApplicationForm',
      formUrlMobile: '/pages/synergy/ErpAuditTransferApplicationForm',
      beanName: 'erpAuditTransferApplicationServiceImpl',
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
      this.initDataList()
      // this.initDisclaimerDetailList()
    } else {
      this.initForm()
      this.initBillNo()
    }
    this.initDictConfig()
  },
  onReady() {
    this.$refs.projectSelect.$on('change', (event) => {
      this.projectChangeHandle(event)
    })
  },
  onUnload() {
    this.$off('change')
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home',
            })
          }
        },
      })
    },

    // 清空自动带出的字段
    resetAutoFields() {
      this.$set(this.model, 'contractId', null)
      this.$set(this.model, 'contractName', null)
      // 项目编号 projectNo
      this.$set(this.model, 'projectNo', null)
      // 项目承接人 undertaker
      this.$set(this.model, 'undertaker', null)
      // managementTeam 经营团队
      this.$set(this.model, 'managementTeam', null)
      // year 业绩归属年度
      this.$set(this.model, 'year', null)
      // signUnit 签订单位
      this.$set(this.model, 'signUnit', null)
      // ownerUnit 业主单位
      this.$set(this.model, 'ownerUnit', null)
      this.$set(this.model, 'productionTeamId', null)
      this.$set(this.model, 'productionTeam', null)
      // 项目名称
      this.$set(this.model, 'projectName', null)
      this.$set(this.model, 'projectId_dictText', null)
      this.instructionDataSource = []
    },

    async projectChangeHandle(data) {
      if (!data) {
        return
      }
      await this.resetAutoFields()
      // if (data.length === 0) {
      //   return;
      // }
      // productionTeam 生产团队
      let project = data
      this.$set(this.model, 'projectName', project.projectName)
      // 查合同
      await queryContractFinal({ xmmc: this.model.projectId, htlx: 1 }).then(async (res) => {
        if (res.success && !!res.result && !!res.result.records[0]) {
          this.$set(this.model, 'contractId', res.result.records[0].id)
          this.$set(this.model, 'contractName', res.result.records[0].htmc)
          await queryProgressPaymentNode({ contractId: this.model.contractId }).then((res) => {
            if (res.success) {
              if (res.result.length > 0) {
                res.result.forEach((item) => {
                  // nodeName paymentMoney
                  let node = {
                    paymentName: item.nodeName,
                    receivableAmount: item.paymentMoney,
                    refundedAmount: item.realCollectionPaymentMoney,
                    invoicingAmount: item.invoicePaidAmount,
                  }
                  // this.$refs.detailList.dataOne(node, true)
                  this.instructionDataSource.push(node)
                })
              } else {
								// 没有节点信息子表置空
								this.instructionDataSource = []
							}
            } else {
							// 没有收款合同
							this.$set(this.model, 'contractId', null) // 合同id置空
							this.$set(this.model, 'contractName', null) // 合同名称置空
							this.instructionDataSource = [] // 子表数据置空
						}
          })
        }
      })
      // 项目编号 projectNo
      this.$set(this.model, 'projectNo', project.finalNo)
      // 项目承接人 undertaker
      this.$set(this.model, 'undertaker', project.undertaker)
      // managementTeam 经营团队
      this.$set(this.model, 'managementTeam', project.teamName)
      //查出项目档案子表的生产团队
      await queryProjectTaskList({ pageNo:1,pageSize: 999,projectId: project.id }).then((res) => {
        if (res.success) {
          let { records } = res.result
          let teamTextTemp = []
          let teamIdTemp = []
          records.forEach((item) => {
            teamIdTemp.push(item.productTeam)
            teamTextTemp.push(filterMultiDictText(this.dictOptions['teamId'], item.productTeam + ''))
          })
          let productTeamId = teamIdTemp.join(',')
          let productTeamText = teamTextTemp.join(',')
          //塞入翻译过的团队名称并用逗号拼接
          this.$set(this.model, 'productionTeamId', productTeamId)
          this.$set(this.model, 'productionTeam', productTeamText)
        }
      })
      // year 业绩归属年度
      this.$set(this.model, 'year', project.year)
      // signUnit 签订单位
      this.$set(this.model, 'signUnit', project.signUnit)
      // ownerUnit 业主单位
      this.$set(this.model, 'ownerUnit', project.ownerUnit)
    },
    initDictConfig() {
      initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'teamId', res.result)
        }
      })
      // initDictOptions('erp_omc_project_task,category_name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'categoryName', res.result)
      //   }
      // })
      // initDictOptions('erp_employee_file,name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'empId', res.result)
      //   }
      // })
      initDictOptions('erp_omc_project,project_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'projectId', res.result)
        }
      })
      // //款项名称
      // initDictOptions('erp_progress_payment_node,node_name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'paymentName', res.result)
      //   }
      // })
      // //豁免类型
      // initDictOptions('exemption_type').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'exemptionType', res.result)
      //   }
      // })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
      //   this.calculateTotalAmount(this.formData)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    // 新增物料
    handleAddMember() {
      this.index = null
      this.showFormModal = true
    },
    //子表保存触发回调
    // calculateTotalAmount(data) {
    //   //计算子表总金额
    //   if (data && data.length > 0) {
    //     let temp = data.reduce(function (prev, cur) {
    //       return new Decimal(cur.achievementsMoney).add(new Decimal(prev))
    //     }, new Decimal(0))
    //     this.$set(this.model, 'reimbursementAmount', temp.toNumber())
    //   } else {
    //     this.$set(this.model, 'reimbursementAmount', null)
    //   }
    // },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({})
      this.model.billNo = res.result
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    //查询任务信息子表数据
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
      this.projectIdBackups = this.model.projectId
    },
    //查询任务信息子表数据
    async initDataList() {
      const response = await queryErpAuditTransferApplicationInfo({ mainId: this.id, pageSize: 999 })
      const data = response.success ? response.result.records : []
      this.instructionDataSource = data
    },
    //加载免责信息子表数据
    // async initDisclaimerDetailList() {
    //   const response = await queryDisclaimerDetailList({ mainId: this.id, pageSize: 999 })
    //   const data = response.success ? response.result.records : []
    //   this.formData = data
    // },
    validateForm() {
      return this.$refs.form.validate()
    },
    getCreateTime() {
      let createTime = this.model.createTime
      let date = createTime.substring(0, 10)
      return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日'
    },
    setBpmBizTitle() {
      var projectName = filterMultiDictText(this.dictOptions['projectId'], this.model.projectId + '')
      this.$set(
        this.model,
        'bpmBizTitle',
        '移交申请-' + (this.model.projectId?projectName +'-':'') +this.userInfo?.employee?.name +'-' +moment(this.model.createTime).format('YYYY-MM-DD'),
      )
    },
    checkContractId() {
      // 有没有带出收款合同
      if (!this.model.contractId) {
        this.$u.toast('该项目还未签收款合同!')
        return Promise.reject('该项目还未签收款合同!')
      }
    },
    // checkDetail() {
    //   let checked = true
    //   this.model.auditLitigationDetail.forEach((detail) => {
    //     if (!detail.paymentMoney) {
    //       checked = false
    //     }
    //   })
    //   if (!checked) {
    //     this.$u.toast('请完善诉讼信息!')
    //     // this.confirmLoading = false;
    //     // this.$emit('unButtonDisable');
    //   }
    //   return checked
    // },
    async onSubmit() {
      await this.validateForm()
      
      await this.checkContractId()
      this.setBpmBizTitle()
      // 子表
      this.model.details = this.instructionDataSource
      // 检查子表的必填项
      // let checked = this.checkDetail()
      // if (!checked) {
      //   return
      // }
			this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          // var that = this
          this.isSubmit = true
          // 获取流程列表
          if (this.model.id) {
            this.getProcessList(this.model.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              this.getProcessList(response.result)
            }
          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    async onDraft() {
      // await this.validateForm()
      this.isSubmit = true
      // this.checkContractId()
      this.setBpmBizTitle()
      // 子表
      this.model.details = this.instructionDataSource
      // 检查子表的必填项
      // let checked = this.checkDetail()
      // if (!checked) {
      //   return
      // }
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.isSubmit = true
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home',
                })
              }
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
  },
}
</script>
    
    <style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
    